$(function () {

    intInputChecked();

    //保存角色授权
    $("body").on("click","#save-role-funtion",function () {
        saveRoleFunction(1);
    }).on('click','#cancel-save',function () {
        window.location.href = baseloaction +'/admin/manage/role/listSysRole';
    }).on('click','.last_step',function(){
        saveRoleFunction(2);
    });

    /**
     * 保存角色授权信息（用于第二步）
     */
    function saveRoleFunction(type){
        var functionIds = $("input[name=functionIds]:checked");
        functionIds = functionIds.map(function(){
            return this.value;
        }).get().join(",");
        var roleId = $("input[name=roleId]").val();
        $.ajax({
            url: baseloaction + '/admin/manage/role/addSubjectAndFunctionToRole',
            data:{
                'functionIds':functionIds,
                'roleId':roleId
            },
            dataType:'JSON',
            type:'post',
            success:function (result) {
                if(result.success==false){
                    icModale(0,result.message);
                }else{
                    if(type==1){
                        VerifyEyeUserRoles();
                    }else if(type==2){
                        //返回第一步
                        window.location.href = baseloaction +'/admin/manage/role/initUpdateRole?type='+typeTo+'&roleId='+$('input[name="roleId"]').val();
                    }

                }
            },
            error:function (error) {
                icModale(0,'系统错误，保存角色授权信息失败');
            }
        });
    }

    /**
     * 保存角色授权信息（用于第二步）
     */
    function VerifyEyeUserRoles(){
        $.ajax({
            url: baseloaction + '/admin/manage/role/VerifyEyeUserRoles',
            data:$("#subjectAndFunctionForm").serialize(),
            dataType:'JSON',
            type:'post',
            success:function (result) {
                if(result.success==false){
                    var context = '<div class="text-center pt10 mt20 pl20 pr20">' +
                        '<p><span class="fs16">你修改了当前账号角色的权限,<br>需要重新登录，才可使用新权限</span></p>'+
                        '</div>';
                    parent.layer.confirm(
                        context,
                        {
                            type: 1,
                            title:'友情提示：',
                            area: ['380px'],
                            offset: 'auto',
                            closeBtn:0,
                            btn:['保存，不退出登录','退出登录'],
                            btnAlign : 'c'
                        },
                        function (index) {
                            parent.layer.close(index);
                            window.location.href = baseloaction+"/admin/manage/role/listSysRole";
                        },function(index){
                            parent.layer.close(index);
                            $(window.parent.document).find('#rightSignOut i.fa-sign-out').click();
                      });
                }else{
                    icModale(0,result.message);
                    setTimeout(function(){
                        window.location.href = baseloaction+"/admin/manage/role/listSysRole";
                    },1000)
                }
            },
            error:function (error) {
                icModale(0,'系统错误');
            }
        });
    }


    /**
     * 初始化多选框选择状态
     */
    function intInputChecked() {
        /**
         *
         $('input').iCheck('check');   //将输入框的状态设置为checked
         $('input').iCheck('uncheck'); //移除 checked 状态
         $('input').iCheck('toggle');  //toggle checked state
         $('input').iCheck('disable'); //将输入框的状态设置为 disabled
         $('input').iCheck('enable');  //移除 disabled 状态
         $('input').iCheck('update');  //apply input changes, which were done outside the plugin
         $('input').iCheck('destroy'); //移除iCheck样式
         *
         *
         *
         *
         * ifClicked 	 用户点击了自定义的输入框或与其相关联的label
         ifChanged 	 输入框的 checked 或 disabled 状态改变了
         ifChecked 	 输入框的状态变为 checked
         ifUnchecked 	 checked 状态被移除
         ifDisabled 	 输入框状态变为 disabled
         ifEnabled 	 disabled 状态被移除
         ifCreated 	 输入框被应用了iCheck样式
         ifDestroyed 	 iCheck样式被移除
         */
        //点击全部系统与功能模块
        $("#all-function").on('ifClicked',function (evnt) {
            if(evnt.target.checked){
                $(".all-functionBox").find('input:checkbox').iCheck('uncheck');
            }else{
                $(".all-functionBox").find('input:checkbox').iCheck('check');
            }
        });
        //点击一级权限
        $(".parent-function-box").find('input:checkbox').on('ifClicked',function (evnt) {
            var _this = $(this);
            var childList = $(_this.parents('.parent-function-box')[0]).next('.child-function-box');
            if(evnt.target.checked){
                childList.find('input:checkbox').iCheck('uncheck');
                $("#all-function").iCheck('uncheck');//设置全选为不选中状态
            }else{
                childList.find('input:checkbox').iCheck('check');
                checkAllSelectStatus();
            }
        });
        //点击二级权限
        $(".two-level-child").find('input:checkbox').on('ifClicked',function (evnt) {
            var _this = $(this);
            var childList = $(_this.parents(".two-level-child")[0]).next('.three-level-child');
            var parent = $(_this.parents('.child-function-box').prev(".parent-function-box")[0]);
            if(evnt.target.checked){
                childList.find('input:checkbox').iCheck('uncheck');
                //如果二级不选中，则判断是否还有选中的二级，如果没有则把一选中状态去掉
                var twoLevelCheckedList = $(_this.parents('.child-function-box')[0]).find(".two-level-child input:checked");
                if((twoLevelCheckedList.length-1) ==0){
                    parent.find('input:checkbox').iCheck('uncheck');
                }
                $("#all-function").iCheck('uncheck');//设置全选为不选中状态
            }else{
                childList.find('input:checkbox').iCheck('check');
                //二级只选中，一级也跟着选中
                parent.find('input:checkbox').iCheck('check');
                checkAllSelectStatus();
            }
        });

        //点击第三级权限
        $(".three-level-child").find('input:checkbox').on('ifClicked',function (evnt) {
            var _this = $(this);
            var threeParent = $(_this.parents('.three-level-child')[0]);
            var twoParent = $(_this.parents('.child-function-box')[0]);
            if(evnt.target.checked){
                $("#all-function").iCheck('uncheck');//设置全选为不选中状态
                var threeSelectCount = threeParent.find('input:checked').length -1;
                if(threeSelectCount==0){
                    //设置二级不选中
                    threeParent.prev('.two-level-child').find('input:checkbox').iCheck('uncheck');
                    var twoSelectCount = $(_this.parents('.child-function-box')[0]).find(".two-level-child input:checked").length;
                    if(twoSelectCount==0){
                        //设置一级不选中
                        twoParent.prev('.parent-function-box').find('input:checkbox').iCheck('uncheck');
                    }
                }
            }else{
                //设置二级选中
                threeParent.prev('.two-level-child').find('input:checkbox').iCheck('check');
                //设置一级选中
                twoParent.prev('.parent-function-box').find('input:checkbox').iCheck('check');
                checkAllSelectStatus();
            }
        });
    }

    /**
     * 检测全选按钮是否要选中
     */
    function checkAllSelectStatus() {
        var sumLen = $("input[name=functionIds]").length;
        var selectLen = $("input[name=functionIds]:checked").length + 1;
        if(sumLen==selectLen){
            $("#all-function").iCheck('check');//设置全选为选中状态
        }
    }
});
